﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlServerCe;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Kiss.Mobile
{
    public static class HandlerHelper
    {
        public static T[] GetObjects<T>(string sql) where T : new()
        {
            List<T> objects = new List<T>();
            SqlCeCommand command = Common.Values.DatabaseConnection.CreateCommand();
            command.CommandText = sql;
            SqlCeDataReader reader = command.ExecuteReader();
            Type type = typeof(T);
            while(reader.Read())
            {
                T entity = new T();
                for(int i = 0; i < reader.FieldCount; i++)
                {
                    if(reader[i] != DBNull.Value)
                    {
                        PropertyInfo propertyInfo = type.GetProperty(reader.GetName(i));
                        propertyInfo.SetValue(entity, reader[i], null);
                    }
                }
                objects.Add(entity);
            }
            return objects.ToArray();
        }

        public static void UpdateObject<T>(T entity, string sql)
        {
            SqlCeCommand command = Common.Values.DatabaseConnection.CreateCommand();
            command.CommandText = sql;
            SqlCeResultSet resultSet = command.ExecuteResultSet(ResultSetOptions.Updatable);
            resultSet.Read();
            Type type = typeof(T);
            for(int i = 0; i < resultSet.FieldCount; i++)
            {
                PropertyInfo propertyInfo = type.GetProperty(resultSet.GetName(i));
                object value = propertyInfo.GetValue(entity, null);
                if(resultSet.GetValue(i) == DBNull.Value)
                {
                    if(value != null)
                        resultSet.SetValue(i, value);
                }
                else
                {
                    if(!value.Equals(resultSet.GetValue(i)))
                        resultSet.SetValue(i, value);
                }
            }
            resultSet.Update();
        }
    }
}
